package il.ac.technion.wiki.impl;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import il.ac.technion.wiki.api.IContentImporter;

public class WikiImporter implements IContentImporter {	
	static String[] handledContentType = {"text/html", "application/xhtml+xml", "text/xml"}; 
	@Override
	public String[] handledContentTypes() {
		return handledContentType;
	}

	@Override
	public String process(byte[] content) throws ContentException {
		String res = new String(content, Charset.defaultCharset());
		//phase 1: remove comments.
		String[] arr = res.split("\\<\\!\\-\\-");
		StringBuilder sb = new StringBuilder();
		if (arr.length == 0)
			return "";
		sb.append(arr[0]);
		for(int i=1; i<arr.length; ++i){
			String tempArr[] = arr[i].split("\\-\\-\\>");
			if (tempArr.length > 2){
				for (int j=1; j < tempArr.length - 1; ++j){
					sb.append(tempArr[j]);
					sb.append("-->");
				}
			}
			sb.append(tempArr[tempArr.length - 1]);
		}
		res = sb.toString();
		//phase 2: remove all other comments
		arr = res.split("\\<");
		sb = new StringBuilder();
		if (arr.length == 0)
			return "";
		sb.append(arr[0]);
		for(int i=1; i<arr.length; ++i){
			String tempArr[] = arr[i].split(">");
			if (tempArr.length > 2){
				for (int j=1; j < tempArr.length - 1; ++j){
					sb.append(tempArr[j]);
					sb.append(">");
				}				
			}
			if (tempArr.length > 1){
				sb.append(tempArr[tempArr.length - 1]);
			}			
		}
		return htmlDecode(sb.toString());		
	}
	
	final static Map<String, String> htmlDecodeMap;
	static{
		htmlDecodeMap = new HashMap<String, String>();
		htmlDecodeMap.put("&nbsp;", " ");
		htmlDecodeMap.put("&quot;", "\"");
		htmlDecodeMap.put("&amp;", "&");
		htmlDecodeMap.put("&lt;", "<");
		htmlDecodeMap.put("&gt;", ">");
	}
	
	String htmlDecode(String html){
		String[] arr = html.split("\\&");
		if (arr.length == 0)
			return "";
		StringBuilder sb = new StringBuilder();
		sb.append(arr[0]);
		for(int i=1; i < arr.length; ++i){
			for (String key: htmlDecodeMap.keySet()){
				if (arr[i].startsWith(key)){
					sb.append(htmlDecodeMap.get(key) + arr[i].substring(key.length()));
					break;
				}
			}
		}
		return sb.toString();
	}
}
